package com.ljq.rpc.server.Listens;

import com.ljq.rpc.annotations.Register;
import com.ljq.rpc.annotations.ServerComponent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

@ServerComponent
public class RegisterApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    private volatile AtomicBoolean isInit=new AtomicBoolean(false);

    private static Map<String, Object> serviceContext = new HashMap<>();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(!isInit.compareAndSet(false,true)) {
            return;
        }
        start(event);
    }

    /**
     * rpc代理初始化
     * @param event
     */
    private void start(ContextRefreshedEvent event){
        ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) event.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Register.class);
        for(Map.Entry<String,Object> entry:beansWithAnnotation.entrySet()){
            for(Class<?> service:entry.getValue().getClass().getInterfaces()){
                serviceContext.put(service.getSimpleName(),entry.getValue());
            }
        }
        System.out.println("服务注册完成");
    }

    public static Object getBean(String name){
        return serviceContext.get(name);
    }

    public static Class<?> getClazz(String name){
        return serviceContext.get(name).getClass();
    }

}
